﻿/*
' DotNetNuke® - http://www.dotnetnuke.com
' Copyright (c) 2002-2009
' by DotNetNuke Corporation
'
' Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
' documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
' the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
' to permit persons to whom the Software is furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all copies or substantial portions 
' of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
' DEALINGS IN THE SOFTWARE.
*/

using System;
using MbUnit.Framework;
using WatiN.Core;
using DotNetNuke.Tests.UI.WatiN.Common;
using Gallio.Framework;
using DotNetNuke.Tests.UI.WatiN.Utilities;
using System.Configuration;
using WatiN.Core.DialogHandlers;
using DotNetNuke.Tests.UI.WatiN.Common.WatiNObjects;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Collections.Generic;




namespace DotNetNuke.Tests.UI.WatiN.AdministratorTests
{
    [TestFixture]
    
    public class AdminNewslettersTests : ATBase
    {
        #region Test Setup and TearDown

        [SetUp]
        public void SetUp()
        {
            
            SetUpTest();
        }

        [TearDown]
        public void TearDown()
        {
            TearDownTest();
        }

        #endregion

        #region Tests

        [Test]
        public void Send_Newsletter_To_Sync()
        {
            //Arrange
            WatiNBase homePage = new WatiNBase(ieInstance, SiteURL, DatabaseName);
            LoginPage loginPage = new LoginPage(homePage);
            //Delete any files in the test EmailAddress folder
            homePage.DeleteFilesInTestEmails();
            //Edit the web.config file so that Emails are sent to a local folder
            WebConfigManager.UpdateConfig(PhysicalPath);

           
            loginPage.LoginUser(TestUsers.Host.UserName, TestUsers.Host.Password);
            ieInstance.GoTo(SiteURL + "/tabid/16/portalid/0/Default.aspx");
            HostSettingsPage hostSettings = new HostSettingsPage(homePage);
            hostSettings.SetSMTPSettings("support@dnn.com", "localhost");

            //Add Three users
            ieInstance.GoTo(SiteURL + "/Admin/UserAccounts.aspx");
            UserPage userPage = new UserPage(homePage);
            userPage.AddUser(TestUsers.User1.UserName, TestUsers.User1.Password, TestUsers.User1.FirstName, TestUsers.User1.LastName, TestUsers.User1.EmailAddress, TestUsers.User1.DisplayName);
            System.Threading.Thread.Sleep(2000);
            //This user intentionally has the same EmailAddress as user1
            userPage.AddUser(TestUsers.User2.UserName, TestUsers.User2.Password, TestUsers.User2.FirstName, TestUsers.User2.LastName, TestUsers.User1.EmailAddress, TestUsers.User2.DisplayName);
            System.Threading.Thread.Sleep(2000);
            userPage.AddUser(TestUsers.User3.UserName, TestUsers.User3.Password, TestUsers.User3.FirstName, TestUsers.User3.LastName, TestUsers.User3.EmailAddress, TestUsers.User3.DisplayName);
            System.Threading.Thread.Sleep(2000);
            // Delete The Email files
            homePage.DeleteFilesInTestEmails();

            //Act 
            ieInstance.GoTo(SiteURL + "/Admin/Newsletters.aspx");
            NewsletterPage newsLetters = new NewsletterPage(homePage);
            newsLetters.CheckRoleCheckBoxByName("Subscribers");
            newsLetters.CheckRoleCheckBoxByName("Administrators");
            newsLetters.SubjectField.Value = "Testmail from [Portal:Portalname]";
            newsLetters.MessageTabLink.Click();
            newsLetters.SelectRadioButtonByName(ieInstance, "BASIC");
            System.Threading.Thread.Sleep(2000);
            newsLetters.ContentTextBox.Value = @"Hi [User:Displayname], it is [dateTime:Current|""dddd""]";
            newsLetters.AdvancedSettingTab.Click();
            newsLetters.ReplaceTokensCheckBox.Checked = true;
            newsLetters.SendMethodSelectList.Select("TO: One Message Per Email Address ( Personalized )");
            newsLetters.SelectRadioButtonByName(ieInstance, "S");
            newsLetters.SendButton.Click();
            System.Threading.Thread.Sleep(1500);

            //Assert 
            Assert.IsTrue(Directory.GetFiles(TestEmailPath).Length == 4);
            Assert.IsFalse(string.IsNullOrEmpty(Directory.GetFiles(TestEmailPath)[0]));
            string adminEmailContent = "";
            string user1EmailContent = "";
            string user3EmailContent = "";
            string batchReportContent = "";
            string currentEmailContent;
            System.Threading.Thread.Sleep(5000);
            string[] files = Directory.GetFiles(TestEmailPath);
            foreach (string fileName in files)
            {
                currentEmailContent = File.ReadAllText(fileName);
                if (currentEmailContent.Contains("X-Receiver: " + TestUsers.Admin.Email) )
                {
                    adminEmailContent = currentEmailContent;                    
                }
                else if (currentEmailContent.Contains("X-Receiver: " + TestUsers.Host.Email))
                {
                    batchReportContent = currentEmailContent;
                }
                else if (currentEmailContent.Contains("X-Receiver: " + TestUsers.User1.EmailAddress))
                {
                    user1EmailContent = currentEmailContent;
                }
                else if (currentEmailContent.Contains("X-Receiver: " + TestUsers.User3.EmailAddress))
                {
                    user3EmailContent = currentEmailContent;
                }
            }
            
            //Assert that the email Content is correct 
            DateTime date = DateTime.Now;
            string day = date.DayOfWeek.ToString();
            Assert.IsTrue(adminEmailContent.Contains("Hi " + TestUsers.Admin.DisplayName + ", it is "), "Content: " + adminEmailContent);
            Assert.IsTrue(user1EmailContent.Contains("Hi " + TestUsers.User1.DisplayName + ", it is " ), "Content: " + user1EmailContent);
            Assert.IsTrue(user3EmailContent.Contains("Hi " + TestUsers.User3.DisplayName + ", it is " ), "Content: " + user3EmailContent);

            batchReportContent = ConvertEmailContentFromBase64ToUnicode(batchReportContent);

            Assert.IsTrue(batchReportContent.Contains("EmailRecipients:      3"));
            Assert.IsTrue(batchReportContent.Contains("EmailMessages:        3"));
            Assert.IsTrue(batchReportContent.Contains("No errors occured during sending."));
            Assert.IsTrue(batchReportContent.Contains(TestUsers.Admin.Email));
            Assert.IsTrue(batchReportContent.Contains(TestUsers.User1.EmailAddress));
            Assert.IsTrue(batchReportContent.Contains(TestUsers.User3.EmailAddress));

            // Delete The EmailAddress files
            homePage.DeleteFilesInTestEmails();
        }

        [Test]
        public void Send_To_One_Additional_Address_Sync_Sends_One_Email()
        {
            //Arrange
            WatiNBase homePage = new WatiNBase(ieInstance, SiteURL, DatabaseName);
            LoginPage loginPage = new LoginPage(homePage);
            //Delete any files in the test EmailAddress folder
            homePage.DeleteFilesInTestEmails();
            //Edit the web.config file so that Emails are sent to a local folder
            WebConfigManager.UpdateConfig(PhysicalPath);


            loginPage.LoginUser(TestUsers.Host.UserName, TestUsers.Host.Password);
            ieInstance.GoTo(SiteURL + "/tabid/16/portalid/0/Default.aspx");
            HostSettingsPage hostSettings = new HostSettingsPage(homePage);
            hostSettings.SetSMTPSettings("support@dnn.com", "localhost");
            homePage.DeleteFilesInTestEmails();

            //Act 
            ieInstance.GoTo(SiteURL + "/Admin/Newsletters.aspx");
            NewsletterPage newsLetters = new NewsletterPage(homePage);


            newsLetters.AdditionalEmailsField.Value = "additional@test.com";
            newsLetters.FromAddressField.Value = "from@test.com";
            newsLetters.ReplyToField.Value = "reply@test.com";
            newsLetters.SubjectField.Value = "Newsletter Test";
            newsLetters.AdvancedSettingTab.Click();
            newsLetters.SelectRadioButtonByName(ieInstance, "S");
            newsLetters.MessageTabLink.Click();
            newsLetters.SelectRadioButtonByName(ieInstance, "BASIC");
            newsLetters.ContentTextBox.Value = "This is the Newsletter";
            newsLetters.SendButton.Click();
            System.Threading.Thread.Sleep(1500);

            //Assert
            Assert.IsTrue(Directory.GetFiles(TestEnvironment.TestEmailPath).Length == 2);
        }

        [Test]
        public void Send_To_One_Additional_Address_Async_Sends_Two_Emails()
        {
            //Arrange
            WatiNBase homePage = new WatiNBase(ieInstance, SiteURL, DatabaseName);
            LoginPage loginPage = new LoginPage(homePage);
            //Delete any files in the test EmailAddress folder
            homePage.DeleteFilesInTestEmails();
            //Edit the web.config file so that Emails are sent to a local folder
            WebConfigManager.UpdateConfig(PhysicalPath);

            homePage.DeleteFilesInTestEmails();
            loginPage.LoginUser(TestUsers.Host.UserName, TestUsers.Host.Password);
            ieInstance.GoTo(SiteURL + "/tabid/16/portalid/0/Default.aspx");
            HostSettingsPage hostSettings = new HostSettingsPage(homePage);
            hostSettings.SetSMTPSettings("support@dnn.com", "localhost");
           

            //Act 
            ieInstance.GoTo(SiteURL + "/Admin/Newsletters.aspx");
            NewsletterPage newsLetters = new NewsletterPage(homePage);

            newsLetters.AdditionalEmailsField.Value = "additional@test.com";
            newsLetters.FromAddressField.Value = "from@test.com";
            newsLetters.ReplyToField.Value = "reply@test.com";
            newsLetters.SubjectField.Value = "Newsletter Test";
            newsLetters.MessageTabLink.Click();
            newsLetters.SelectRadioButtonByName(ieInstance, "BASIC");
            newsLetters.ContentTextBox.Value = "This is the Newsletter";
            newsLetters.SendButton.Click();
            System.Threading.Thread.Sleep(5000);

            //Assert
            Assert.IsTrue(Directory.GetFiles(TestEnvironment.TestEmailPath).Length == 3);
        }

        [Test]
        public void Send_Sync_Sends_To_Correct_Addresses()
        {
            //Arrange
            WatiNBase homePage = new WatiNBase(ieInstance, SiteURL, DatabaseName);
            LoginPage loginPage = new LoginPage(homePage);
            //Delete any files in the test EmailAddress folder
            homePage.DeleteFilesInTestEmails();
            //Edit the web.config file so that Emails are sent to a local folder
            WebConfigManager.UpdateConfig(PhysicalPath);

            homePage.DeleteFilesInTestEmails();
            loginPage.LoginUser(TestUsers.Host.UserName, TestUsers.Host.Password);
            ieInstance.GoTo(SiteURL + "/tabid/16/portalid/0/Default.aspx");
            HostSettingsPage hostSettings = new HostSettingsPage(homePage);
            hostSettings.SetSMTPSettings("support@dnn.com", "localhost");

            //Act 
            ieInstance.GoTo(SiteURL + "/Admin/Newsletters.aspx");
            NewsletterPage newsLetters = new NewsletterPage(homePage);

            newsLetters.AdditionalEmailsField.Value = "additional@test.com";
            newsLetters.FromAddressField.Value = "from@test.com";
            newsLetters.ReplyToField.Value = "reply@test.com";
            newsLetters.SubjectField.Value = "Newsletter Test";
            newsLetters.MessageTabLink.Click();
            newsLetters.SelectRadioButtonByName(ieInstance, "BASIC");
            newsLetters.ContentTextBox.Value = "This is the Newsletter";
            newsLetters.AdvancedSettingTab.Click();
            newsLetters.SelectRadioButtonByName(ieInstance, "S");
            newsLetters.SendButton.Click();

            System.Threading.Thread.Sleep(1500);
            string emailFileName;
            StreamReader emailContents;
            List<string> emailLines;
            string emailLine;
            string subjectLine, fromLine, toLine, replyToLine;
            int pos = 0;

            do
            {
                emailFileName = Directory.GetFiles(@TestEnvironment.TestEmailPath)[pos];
                emailContents = File.OpenText(emailFileName);
                emailLine = emailContents.ReadLine();
                emailLines = new List<string>();
                while (emailLine != null)
                {
                    emailLines.Add(emailLine);
                    emailLine = emailContents.ReadLine();
                }

                fromLine = emailLines.Find(l => l.Contains("From:"));
                toLine = emailLines.Find(l => l.Contains("To:"));
                replyToLine = emailLines.Find(l => l.Contains("Reply-To:"));
                subjectLine = emailLines.Find(l => l.Contains("Subject:"));
                subjectLine = ConvertSubjectLineFromBase64ToUnicode(subjectLine);
                pos++;
            } while (!subjectLine.Equals("Newsletter Test") );

            //Assert
            Assert.Contains(fromLine, "from@test.com");
            Assert.Contains(toLine, "additional@test.com");
            //Assert.Contains(subjectLine, SubjectField);
            Assert.Contains(replyToLine, "reply@test.com");
            //http://support.dotnetnuke.com/issue/ViewIssue.aspx?id=11507&PROJID=2
        }



        #endregion


        private string ConvertSubjectLineFromBase64ToUnicode(string subjectLine)
        {
            //Separate the EmailAddress content from the EmailAddress information
            string subjectLineRegex = @"(?<=(\=\?utf-8\?\w\?)).*(?=\?\=)";
            Match match = Regex.Match(@subjectLine, subjectLineRegex, RegexOptions.Singleline);
            Assert.IsTrue(match.Success, "Could not find content in" + subjectLine);
            
            //Convert the Subject Line
            subjectLine = match.Value;
            byte[] b = System.Convert.FromBase64String(subjectLine);
            String decodedEmailSubject = System.Text.ASCIIEncoding.ASCII.GetString(b);
            return decodedEmailSubject;
        }

        private string ConvertEmailContentFromBase64ToUnicode(string emailContent)
        {
            //Replace any new link characters
            emailContent.Replace(Environment.NewLine, " ");

            //Separate the EmailAddress content from the EmailAddress information
            string contentLineRegex = "(?<=base64).*$";
            Match match = Regex.Match(@emailContent, contentLineRegex, RegexOptions.Singleline);
            Assert.IsTrue(match.Success, "Could not find content in" + emailContent);

            //Convert the EmailAddress content
            emailContent = match.Value;
            byte[] b = System.Convert.FromBase64String(emailContent);
            String decodedEmailContent = System.Text.ASCIIEncoding.ASCII.GetString(b);
            return decodedEmailContent;
        }

        
    }

}

